package commander;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import core.*;


public class CLI {	
	
	/**
	 * Command 'jit init'
	 * @param args
	 * @throws IOException
	 */
	public static void jitInit(String[] args) throws IOException {
		String path = ".";
		if(args.length <= 2) { //get default working path  //用户输入 jit init
			JitInit.init(path); //对当前目录生成一个.jit仓库
		}else if(args[2].equals("-help")){ //see help  //用户输入 jit init -help
			System.out.println("usage: jit init [<path>] [-help]\r\n" +
					"\r\n" +
					"jit init [<path>]:	Create an empty jit repository or reinitialize an existing one in the path or your default working directory.");
		}else {
			path = args[2];
			if(!new File(path).isDirectory()) { //if the working path input is illegal
				System.out.println(path + " is not a legal directory. Please init your repository again. See 'jit init -help'.");
			}else {
				JitInit.init(path); //对指定目录生成一个.jit仓库
			}
		}
	}
	

	/**
	 * Command 'jit help'.
	 */
	public static void jitHelp() {
		System.out.println("usage: jit [--version] [--help] [-C <path>] [-c name=value]\r\n" +
				"           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]\r\n" +
				"           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]\r\n" +
				"           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]\r\n" +
				"           <command> [<args>]\r\n" +
				"\r\n" +
				"These are common Jit commands used in various situations:\r\n" +
				"\r\n" +
				"start a working area\r\n" +
				"   init       Create an empty Jit repository or reinitialize an existing one\r\n" +
				"\r\n" +
				"work on the current change\r\n" +
				"   add        Add file contents to the index\r\n" +
				"   reset      Reset current HEAD to the specified state\r\n" +
				"   rm         Remove files from the working tree and from the index\r\n" +
				"\r\n" +
				"examine the history and state\r\n" +
				"   log        Show commit logs\r\n" +
				"   status     Show the working tree status\r\n" +
				"\r\n" +
				"grow, mark and tweak your common history\r\n" +
				"   branch     List, create, or delete branches\r\n" +
				"   checkout   Switch branches or restore working tree files\r\n" +
				"   commit     Record changes to the repository\r\n" +
				"   diff       Show changes between commits, commit and working tree, etc\r\n" +
				"   merge      Join two or more development histories together\r\n" +
				"\r\n" +
				"'jit help -a' and 'jit help -g' list available subcommands and some\r\n" +
				"concept guides. See 'jit help <command>' or 'jit help <concept>'\r\n" +
				"to read about a specific subcommand or concept.");
	}

	/**
	 * Command 'jit add'.
	 */
	public static void jitAdd(String[] args) throws Exception {
		if(args.length <= 2) { //用户输入 jit add
			System.out.println("Nothing specified, nothing added.");
		}
		else if(args[2].equals("-help")){ //用户输入 jit add -help
			System.out.println("usage: jit add <path>" +
					"\r\n" +
					"jit add <path>: Add file or files in directory into stage area.");
		}
		else {
			String path = args[2];
			if (new File(path).exists()) JitAdd.add(path);
			else System.out.println("fatal: pathspec '" + path + "' did not match any files\n");
		}

	}

	/**
	 * Command 'jit rm'.
	 */
	public static void jitRm(String[] args) throws Exception {
		if (args.length <= 2) { // 用户输入 jit rm
			System.out.println("fatal: No pathspec was given. Which files should I remove?");
		}
		else if(args[2].equals("-help")){ //用户输入 jit rm -help
			System.out.println("usage: jit rm <file>" +
					"\r\n" +
					"jit rm <file>: Remove file from stage area.");
		}
		else {
			String path = args[2];
			JitRm.remove(path);
		}
	}

	/**
	 * Command 'jit commit'.
	 */
	public static void jitCommit(String[] args) throws Exception {
		if (args.length <= 2 || args[2].equals("-help")) { // 用户输入 jit commit 或者 jit commit -help
			System.out.println("usage: jit commit -m <message>" +
					"\r\n" +
					"jit commit -m <message>: Commit all the files on stage and clear stage. ");
		}
		else if (!args[2].equals("-m")){ //用户输入 jit commit ???
			System.out.println("usage: jit commit -m <message>" +
					"\r\n" +
					"Please use -m parameter to specify commit message");
		}
		else {
			if (args.length <= 3) { // 用户输入 jit commit -m
				System.out.println("usage: jit commit -m <message>" +
						"\r\n" +
						"Please make sure to input some commit message enclosing with \" ");
			}
			else { // 连接commit message为字符串，将“替换
				String commitMsg = "";
				for (int i=3; i<args.length; i++) {
					commitMsg += args[i] + " ";
				}
				commitMsg = commitMsg.replace("\"", "");
				JitCommit.commit(commitMsg);
			}
		}

	}

	/**
	 * Command 'jit log'.
	 */
	public static void jitLog(String[] args) throws Exception {
		if (args.length >= 3) { // 有多余参数或者 jit log -help
			if (args[2].equals("-help"))
				System.out.println("usage: jit log" +
					"\r\n" +
					"jit log: Display commit history.");
			else {
				System.out.println("Invalid command.\n" +
						"usage: jit log" +
						"\r\n" +
						"jit log: Display commit history.");
			}
		}
		else {
			JitLog.getLogHistory();
		}

	}

	/**
	 * Command 'jit reset'.
	 */
	public static void jitReset(String[] args) throws Exception {
		if (args.length <= 2 || args[2].equals("-help")) { // 用户输入 jit reset 或者 jit reset -help
			System.out.println("usage: jit reset [<commit>] [--mixed | --soft | --hard] " +
					"\r\n" +
					"jit reset [<commit>] [--mode]: Reset current HEAD to the specified state. " +
					"\r\n" +
					"jit reset [<commit>]: Reset in mixed mode." +
					"\r\r\n" +
					"--mixed\r\rreset HEAD and index\n" +
					"--soft\r\rreset only HEAD\n" +
					"--hard\r\rreset HEAD, index and working tree"
			);
		}
		else if (args.length <= 3) { // no --mode parameter
			if (args[2].length() < 6) { // 要求至少6位
				System.out.println("Please input at least first 6 characters of commit id");
			}
			else {
				JitReset.resetMode("--mixed", args[2]);
			}
		}
		else {
			if (args[3].equals("--soft") || args[3].equals("--mixed") || args[3].equals("--hard")) {
				if (args[2].length() < 6) { // 要求至少6位
					System.out.println("Please input at least first 6 characters of commit id");
				}
				else {
					JitReset.resetMode(args[3], args[2]);
				}
			}
			else {
				System.out.println("usage: jit reset [<commit>] [--mixed | --soft | --hard]");
			}
		}
	}

	/**
	 * Command 'jit branch'.
	 */
	public static void jitBranch(String[] args) throws Exception {
		String jitBranchHelpMsg = "usage: jit branch [-d] [<branch name>] " +
				"\r\n" +
				"jit branch: List all local branches. " +
				"\r\n" +
				"jit branch [<branch name>]: Create a new branch without switching to it." +
				"\r\n" +
				"jit branch -d [<branch name>]: Delete branch.";
		if (args.length == 2) { // jit branch
			JitBranch.printBranch();
		}
		else if (args.length >= 3) {
			if (args[2].equals("-help")) { // jit branch -help
				System.out.println(jitBranchHelpMsg);
			}
			else if (args[2].equals("-d")) {
				if (args.length >= 4) {
					JitBranch.deleteBranch(args[3]);
				}
				else {
					System.out.println("fatal: branch name required");
				}
			}
			else if (args.length == 3) {
				JitBranch.createBranch(args[2]);
			}
			else {
				System.out.println(jitBranchHelpMsg);
			}
		}
		else {
			System.out.println(jitBranchHelpMsg);
		}
	}

	/**
	 * Command 'jit checkout'.
	 */
	public static void jitCheckout(String[] args) throws Exception {
		String jitCheckoutHelpMsg = "usage: jit checkout [-b] [<branch name>] " +
				"\r\n" +
				"jit checkout [<branch name>]: Switch to branch and update working directory." +
				"\r\n" +
				"jit checkout -b [<branch name>]: Create a new branch and switch to it.";
		if (args.length == 2) { // jit checkout
			System.out.println(jitCheckoutHelpMsg);
		}
		else if (args.length >= 3) {
			if (args[2].equals("-help")) { // jit branch -help
				System.out.println(jitCheckoutHelpMsg);
			}
			else if (args[2].equals("-b")) {
				if (args.length >= 4) {
					JitCheckout.switchBranch(args[3]);
				}
				else {
					System.out.println("fatal: branch name required");
				}
			}
			else if (args.length == 3) {
				JitCheckout.switchBranch(args[2]);
			}
			else {
				System.out.println(jitCheckoutHelpMsg);
			}
		}
		else {
			System.out.println(jitCheckoutHelpMsg);
		}
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("请输入指令：(q终止程序)");
			String command = sc.nextLine();
			if (command.equals("q")) return;

			String[] content = command.split(" ");
			if(content.length <= 1 || content[1].equals("help")) {
				jitHelp();
			}
			else {
				if(content[1].equals("init")) {
					jitInit(content);
				}
				else if (content[1].equals("add")) {
					jitAdd(content);
				}
				else if (content[1].equals("rm")) {
					jitRm(content);
				}
				else if (content[1].equals("commit")) {
					jitCommit(content);
				}
				else if (content[1].equals("log")) {
					jitLog(content);
				}
				else if (content[1].equals("reset")) {
					jitReset(content);
				}
				else if (content[1].equals("branch")) {
					jitBranch(content);
				}
				else if (content[1].equals("checkout")) {
					jitCheckout(content);
				}
				else {
					System.out.println("jit: " + content[1] + "is not a git command. See 'git help'.");
				}
			}
		}
	}
}
